package com.surfilter.geet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringParseUtils {

    private static Logger logger = LoggerFactory.getLogger(StringParseUtils.class);

    private static String dzRegex = "[^：^:]*(省|市|区)[^：^\\s]*";

    private static String dhRegex = "([\\(|（]?\\s*([0-9]+(-|\\s)*)+[\\)|）]?)?\\s*([0-9]+(-|\\s)*)+";

    public static String parseDz(String dz) {
        String result = "";
        try {
            if (dz != null) result = NumFormatUtils.parseString(dz, dzRegex, false);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("匹配地址异常：" + dz, e);
        }
        return result;
    }

    public static String parseDh(String dh) {
        String result = "";
        try {
            if (dh != null) result = parseString(dh, dhRegex, false, 5);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("匹配电话异常：" + dh, e);
        }
        return result;
    }

    public static String parseString(String text, String regex, boolean regexAll, int length) {
        StringBuilder strb = new StringBuilder();
        Pattern patt = Pattern.compile(regex);
        Matcher match = patt.matcher(text);
        while (match.find()) {
            String value = match.group();
            if (value.length() >= length) {
                strb.append(match.group());
                if (!regexAll) break;
            }
        }
        return strb.toString();
    }

    public static void main(String[] args) {
        String value = "027 - 8555 1080";
        System.out.println(parseDh(value));
    }


    public static String parseString(String text, String regex, boolean regexAll) {
        StringBuilder strb = new StringBuilder();
        Pattern patt = Pattern.compile(regex);
        Matcher match = patt.matcher(text);
        while (match.find()) {
            strb.append(match.group());
            if (!regexAll) break;
        }
        return strb.toString();
    }

    public static String parseString(String text, String regex, int regexAll) {
        String target = null;
        Pattern patt = Pattern.compile(regex);
        Matcher match = patt.matcher(text);
        int i = 0;
        while (match.find()) {
            i++;
            target = match.group();
            if (regexAll == i) break;
        }
        return target;
    }

}
